#coding: utf-8
class CulturalHeritage::Collection < ActiveRecord::Base
  belongs_to :obj_collection_state, :class_name => 'CulturalHeritage::CollectionState',  :foreign_key => 'state'  
  belongs_to :obj_owner, :class_name => 'Security::Person',  :foreign_key => 'owner'
  belongs_to :obj_cultural_institution, :class_name => 'CulturalHeritage::CulturalInstitution',  :foreign_key => 'cultural_institution'

  has_many :cultural_heritages, :class_name => 'CulturalHeritage::CulturalHeritage',  :foreign_key => 'collection'
  has_many :list_photos, :class_name => 'CulturalHeritage::CollectionPhoto',  :foreign_key => 'collection'
  #accepts_nested_attributes_for :list_photos

  default_scope where("cultural_heritage_collections.deleted = 0")

  validates :name, :presence => {:message => "El nombre es requerido"}
  validates :owner, :presence => {:message => "Debe seleccionar un propietario"}
  #validates :cultural_institution, :presence => {:message => "Debe seleccionar la institución cultural"}
  validates :original_size, :presence => {:message => "Debe indicar un tamaño para la colección"}

  def str_state
    if state.blank?
      return ""
    else
      obj_state = CulturalHeritage::CollectionState.find(state)
      return obj_state.name
    end
  end

  def str_owner
    if owner.blank?
      return ""
    else
      obj_owner = Security::Person.find(owner)
      return obj_owner.name + " "  + obj_owner.lastname
    end
  end

  def str_cultural_institution
    if cultural_institution.blank?
      return ""
    else
      obj_cultural_institution = CulturalHeritage::CulturalInstitution.find(cultural_institution)
      return obj_cultural_institution.name
    end
  end

  def title_name_code
     return "[Pukara] Patrimonio Material Inmueble " + name
  end

  def self.count_cultural_institution_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_collections.cultural_institution = ? and (cultural_heritage_collections.deleted = ?) ",id,0],:select=>"count(*) as 'collections'")[0].collections.to_i
  end

  def self.count_person_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_collections.owner = ? and (cultural_heritage_collections.deleted = ?) ",id,0],:select=>"count(*) as 'collections'")[0].collections.to_i
  end
  
  def self.count_collection_state_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_collections.state = ? and (cultural_heritage_collections.deleted = ?) ",id,0],:select=>"count(*) as 'collections'")[0].collections.to_i
  end

  def erasable
    care = CulturalHeritage::CollectionPhoto.count_collection_type_dependencies(id)
    if care>0
      return "Imposible borrar. Existen dependencias en fotos de coleccion"    
    end
    return nil
  end
end
